package com.banciyuan.bcywebview.utils.http;

import com.qiniu.android.dns.DnsManager;
import com.qiniu.android.dns.IResolver;
import com.qiniu.android.dns.NetworkInfo;
import com.qiniu.android.dns.http.DnspodFree;
import com.qiniu.android.dns.local.AndroidDnsServer;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * Created by squall on 2016/5/31.
 */
public class HttpDns {

    private static DnsManager dns;

    public HttpDns() {
        IResolver[] resolvers = new IResolver[2];
        resolvers[0] = AndroidDnsServer.defaultResolver();
        resolvers[1] = new DnspodFree();
        if (dns == null) {
            dns = new DnsManager(NetworkInfo.normal, resolvers);
        }
    }

    public String getIp(String domain) {
        FutureTask<String> future = new FutureTask<>(new Task(domain));
        Thread child = new Thread(future);
        child.start();
        String ip = "";
        try {
            ip = future.get(200, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

    public String getIpSyns(String domain) {
        try {
            String[] arrays = dns.query(domain);
            if (arrays != null) {
                return arrays[0];
            } else {
                return "";
            }
        } catch (IOException e) {
            return "";
        }
    }

    private class Task implements Callable<String> {
        private String domain;

        public Task(String domain) {
            this.domain = domain;
        }

        @Override
        public String call() throws Exception {
            String[] arrays = dns.query(domain);
            if (arrays != null) {
                return arrays[0];
            } else {
                return "";
            }
        }
    }
}
